using FluentFTP;

namespace Digitalmes.Infrastructure.Ftp;

/// <summary>
/// <see cref="IFluentFtpClient"/> 扩展。
/// </summary>
public static class FluentFtpClientExtensions
{
    /// <summary>
    /// 上传文件到远程服务器。
    /// </summary>
    /// <param name="ftpClient"></param>
    /// <param name="bytes">要上传的文件字节数据。</param>
    /// <param name="remotePath">远程服务器文件。</param>
    /// <param name="isOverwrite">若远程服务器文件存在时，是否覆盖。</param>
    /// <param name="createRemoteDir">若远程服务器目录不存在时，是否创建目录。</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task<bool> UploadFileAsync(this IFluentFtpClient ftpClient,
        byte[] bytes,
        string remotePath,
        bool isOverwrite = true,
        bool createRemoteDir = false,
        CancellationToken cancellationToken = default)
    {
        if (!ftpClient.Client.IsConnected)
        {
            await ftpClient.Client.AutoConnect(cancellationToken);
        }

        var status = await ftpClient.Client.UploadBytes(
            bytes,
            remotePath,
            existsMode: isOverwrite ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip,
            createRemoteDir: createRemoteDir,
            token: cancellationToken);
        return status is FtpStatus.Success || (!isOverwrite && status is FtpStatus.Skipped);
    }

    /// <summary>
    /// 从远程服务器下载文件。
    /// </summary>
    /// <param name="ftpClient"></param>
    /// <param name="remotePath">要下载的远程服务器文件。</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task<byte[]> DownloadFileAsync(this IFluentFtpClient ftpClient, string remotePath, CancellationToken cancellationToken = default)
    {
        if (!ftpClient.Client.IsConnected)
        {
            await ftpClient.Client.AutoConnect(cancellationToken);
        }

        return await ftpClient.Client.DownloadBytes(remotePath, cancellationToken);
    }
}
